package com.lingchen.controller;

import com.lingchen.response.Result;
import com.lingchen.response.ResultUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Author    lingchen
 * Email     838878458@qq.com
 * Time      2018/5/14
 * Function  ...
 */
@Component
public class TestQueue {
    private Logger log = Logger.getLogger(TestQueue.class);
    private volatile boolean isRunning = true;
    private static AtomicInteger count = new AtomicInteger();
    private BlockingQueue<DeferredResult<Result<String>>> queue = new LinkedBlockingQueue<DeferredResult<Result<String>>>(10);

    public TestQueue() {

    }

    public boolean offer(DeferredResult<Result<String>> deferredResult) {
        try {
            return queue.offer(deferredResult, 0, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    public void start() {
        isRunning = true;
        new Thread(new Runnable() {
            public void run() {
                while (isRunning) {
                    try {
                        int a = count.incrementAndGet();
                        DeferredResult<Result<String>> deferredResult = queue.poll(10, TimeUnit.SECONDS);
                        if (deferredResult != null) {
                            log.debug("开始处理-->" + a);
                            Thread.sleep(1000);
                            deferredResult.setErrorResult(ResultUtil.<String>success());
                            log.debug("处理结束-->" + a);
                        } else {
                            log.debug("长时间没任务>" + a);
                            stop();
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        stop();
                    }
                }

            }
        }).start();
    }

    private void stop() {
        log.debug("停止任务");
        isRunning = false;
    }


}
